package ory

import (
	"context"
	client "github.com/ory/hydra-client-go"
)

func NewHydra(ctx context.Context, url string) *Hydra {
	configuration := client.NewConfiguration()
	configuration.Servers = []client.ServerConfiguration{
		{
			URL: url,
		},
	}

	// configuration.HTTPClient.Transport = BasicAuthTransport{
	// 	Username: "foo",
	// 	Password: "bar",
	// }

	// creds := clientcredentials.Config{
	// 	TokenURL:     "http://hydra.localhost:4444/oauth2/token",
	// 	ClientID:     "my-client",
	// 	ClientSecret: "my-secret",
	// 	Scopes:       []string{"scope-a", "scope-b"},
	// }
	// configuration.HTTPClient = creds.Client(ctx)

	// httpClient := new(http.Client)
	// rt := WithHeader(httpClient.Transport)
	// rt.Set("X-Forwarded-Proto", "https")
	// httpClient.Transport = rt

	// httpClient := &http.Client{
	// 	Transport: &http.Transport{
	// 		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	// 	},
	// 	Timeout: 10,
	// }
	// configuration.HTTPClient = httpClient

	return &Hydra{
		ctx:           ctx,
		configuration: configuration,
		client:        client.NewAPIClient(configuration),
	}
}

type Hydra struct {
	ctx           context.Context
	configuration *client.Configuration
	client        *client.APIClient
}

func (r *Hydra) OAuth2ClientCreate(req HydraOAuth2ClientCreateReq) (*client.OAuth2Client, error) {
	oAuth2Client := client.NewOAuth2Client()
	oAuth2Client.SetClientId(req.ClientId)
	oAuth2Client.SetClientName(req.ClientName)

	resp, _, err := r.client.AdminApi.CreateOAuth2Client(r.ctx).
		OAuth2Client(*oAuth2Client).
		Execute()

	return resp, err
}
func (r *Hydra) OAuth2Clients(req *HydraOAuth2ClientsReq) ([]client.OAuth2Client, error) {
	clients, _, err := r.client.AdminApi.ListOAuth2Clients(r.ctx).
		Limit(req.Limit).
		Offset(req.Offset).
		ClientName(req.ClientName).
		Execute()

	return clients, err
}
func (r *Hydra) OAuth2TokenRevoke() error {
	_, err := r.client.PublicApi.RevokeOAuth2Token(r.ctx).Token("some_token").Execute()
	return err
}
func (r *Hydra) ConsentChallenge() (*client.ConsentRequest, error) {
	execute, _, err := r.client.AdminApi.GetConsentRequest(r.ctx).ConsentChallenge("consentChallenge_example").Execute()
	return execute, err
}
